<template>
  <div class="main commodity-manage-edit">
    <div class="main-title">
      <h4 v-text="isEdit ? pageTypes[$route.query.pageType] : '商品新建'"></h4>
      <div class="btn-box">
        <el-button
          v-if="$route.query.pageType!=='view'"
          class="filter-item"
          type="success"
          size="small"
          :loading="btnLoading"
          @click="save"
        >保存</el-button>

        <el-button
          v-if="rightsButtons['downShelf'] && $route.query.pageType==='view' && formData.goodsRequest.upshelf === 1"
          class="filter-item"
          type="danger"
          size="small"
          :loading="btnLoading"
          @click="updateStatus"
        >下架</el-button>
        <el-button
          class="filter-item"
          type="primary"
          size="small"
          plain
          @click="$router.push({name: ($store.getters.organizationId===1&&$route.query.goodsType==2)?'commodityPreManage':'commodityManage'})"
        >返回</el-button>
        <el-button
          class="filter-item"
          type="warning"
          size="small"
          v-if="!isEdit"
          @click="clearData(1)"
          plain
        >清空数据缓存</el-button>
      </div>
    </div>
    <el-tabs
      v-model="tab"
      type="border-card"
      @tab-click="syncSkuNumber"
      v-loading="pageLoading"
    >
      <el-tab-pane
        label="基础信息"
        name="base"
      >
        <el-form
          :model="formData"
          :rules="rulesBase"
          size="medium"
          ref="formBase"
          label-width="150px"
          :disabled="$route.query.pageType==='view'"
        >
          <el-form-item
            label="ERP商品名称:"
            prop="goodsRequest.erpGoodsName"
          >
            <el-input
              v-model="formData.goodsRequest.erpGoodsName"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item
            label="APP商品名称:"
            prop="goodsRequest.name"
          >
            <el-input v-model="formData.goodsRequest.name" maxlength="101"></el-input>
          </el-form-item>
          <el-form-item
            label="APP商品副标题:"
            prop="goodsRequest.subName"
          >
            <el-input v-model="formData.goodsRequest.subName" maxlength="101"></el-input>
          </el-form-item>
          <el-form-item
            label="商品款号:"
            prop="goodsRequest.serialNo"
          >
            <el-input
              v-model="formData.goodsRequest.serialNo"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item
            label="ERP商品分类:"
            prop="goodsRequest.erpCategoryName"
          >
            <el-input
              v-model="formData.goodsRequest.erpCategoryName"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item
            label="商品分类:"
            prop="goodsRequest.category"
          >
            <el-select
              v-model="formData.goodsRequest.category"
              placeholder="请选择"
              @change="categoryChange"
            >
              <el-option
                v-for="(item, index) of categoryTree"
                :style="{paddingLeft: `${item._level * 15}px`}"
                :key="index"
                :label="`${item.parentId ? '∟' : ''}${item.name}`"
                :value="item.id+'_'+item.name"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="税收分类：" prop="goodsRequest.taxCode" class="cascader-m">
            <el-input v-model="taxTxt" clearable v-if="taxTxt"/>
            <el-cascader
            v-else
            v-model="tax"
            :options="taxListOptions"
            :filterable="true"
            :props="{label: 'taxName', value: 'taxName', children: 'children', disabled: 'disabled'}"
            @change="getVal"
            :show-all-levels="false"
            :clearable="true"
            ></el-cascader><span class="code">{{this.formData.goodsRequest.taxCode}}</span>
          </el-form-item>
          <el-form-item
            label="商品主图:"
            prop="goodsRequest.image"
          >
            <!--<div>
                            <el-radio :label="1" :key="1" v-model="form.goodsRequest.type">视频</el-radio>
                            <el-radio :label="2" :key="2" v-model="form.goodsRequest.type">图片</el-radio>
                        </div>-->
            <el-upload
              class="avatar-uploader"
              :action="upladUrl"
              name="file"
              :show-file-list="false"
              :before-upload="beforeUpload"
              :on-success="uploadSuccess"
            >
              <img
                v-if="formData.goodsRequest.image"
                :src="formData.goodsRequest.image"
                class="avatar"
              >
              <i
                v-else
                class="el-icon-plus avatar-uploader-icon"
              ></i>
            </el-upload>
          </el-form-item>
          <el-form-item
            label="列表页封面图片:"
            prop="goodsRequest.listCover"
          >
            <el-upload
              class="avatar-uploader"
              :action="upladUrl"
              name="file"
              :show-file-list="false"
              :before-upload="beforeUpload"
              :on-success="uploadListCoverSuccess"
            >
              <img
                v-if="formData.goodsRequest.listCover"
                :src="formData.goodsRequest.listCover"
                class="avatar"
              >
              <i
                v-else
                class="el-icon-plus avatar-uploader-icon"
              ></i>
            </el-upload>
          </el-form-item>
          <el-form-item
            label="秒杀图片:"
            prop="goodsRequest.crushImage"
          >
            <el-upload
              class="avatar-uploader"
              :action="upladUrl"
              name="file"
              :show-file-list="false"
              :before-upload="beforeUpload"
              :on-success="uploadCrushImageSuccess"
            >
              <img
                v-if="formData.goodsRequest.crushImage"
                :src="formData.goodsRequest.crushImage"
                class="avatar"
              >
              <i
                v-else
                class="el-icon-plus avatar-uploader-icon"
              ></i>
            </el-upload>
          </el-form-item>
          <el-form-item
            label="商品图片:"
            prop="goodsRequest.goodsGalleryList"
          >
            <ul class="upload-img-list">
              <draggable
                v-model="formData.goodsRequest.goodsGalleryList"
                :options="{group:'goodsGalleryList'}"
                @start="drag=true"
                @end="drag=false"
              >
                <li
                  class="img-preview"
                  v-for="(item, index) of formData.goodsRequest.goodsGalleryList"
                  :key="index"
                >
                  <img
                    v-if="item.type === 2"
                    :src="item.url"
                    alt=""
                  >
                  <video
                    v-else-if="item.type === 1"
                    autoplay="autoplay"
                    loop="loop"
                  >
                    <source
                      :src="item.url"
                      type="video/mp4"
                    >
                    您的浏览器不支持HTML5 Video
                  </video>
                  <div
                    class="img-preview-mask"
                    v-if="$route.query.pageType!=='view'"
                  >
                    <div class="mask-btn">
                      <i
                        title="删除"
                        class="el-icon-delete"
                        @click="delImg(index)"
                      ></i>
                    </div>
                  </div>
                </li>
              </draggable>
              <li v-if="$route.query.pageType!=='view'">
                <label class="upload-btn">
                  <input
                    type="file"
                    @change="uploadImg"
                  />
                  <i class="el-icon-plus"></i>
                </label>
              </li>
            </ul>
            <div
              v-if="formData.goodsRequest.goodsGalleryList.length>1"
              style="color: red"
            >拖拽已上传的图片可以进行排序</div>
          </el-form-item>
          <!--<el-form-item label="市场价:" prop="goodsRequest.marketValue">
                        <el-input type="number" v-model="formData.goodsRequest.marketValue"></el-input>
                    </el-form-item>
                    <el-form-item label="兰蜜价:" prop="goodsRequest.price">
                        <el-input type="number" v-model="formData.goodsRequest.price" @change="calcPrice"></el-input>
                    </el-form-item>
                    <el-form-item label="大区价:" prop="goodsRequest.regionPrice">
                        <el-input type="number" v-model="formData.goodsRequest.regionPrice" placeholder="自动生成" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="董事价:" prop="goodsRequest.directorPrice">
                        <el-input type="number" v-model="formData.goodsRequest.directorPrice" placeholder="自动生成" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="最高佣金:" prop="goodsRequest.maximumCommission">
                        <el-input type="number" placeholder="须小于兰蜜价" v-model="formData.goodsRequest.maximumCommission" @change="calcPrice"></el-input>
                    </el-form-item>-->
          <el-form-item
            label="用户限购数量:"
            prop="goodsRequest.userQuantity"
          >
            <el-input
              type="number"
              v-model="formData.goodsRequest.userQuantity"
            ></el-input> 填 0 代表不限购
          </el-form-item>
          <el-form-item
            label="简介:"
            prop="goodsRequest.intro"
          >
            <el-input
              type="textarea"
              v-model="formData.goodsRequest.intro"
              maxLength="300"
            ></el-input>
          </el-form-item>
          <el-form-item label="业务首次上架时间:" class="hide-close">
            <el-date-picker
              :disabled="!formData.goodsRequest.firstUpSelfTime"
              v-model="formData.goodsRequest.firstUpSelfTime"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetime"
              placeholder="选择日期时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item
            label="经营模式:"
            prop="goodsRequest.businessModel"
          >
            <el-select
              v-model="formData.goodsRequest.businessModel"
              placeholder="请选择"
            >
              <el-option
                :key="1"
                label="自营"
                :value="1"
              ></el-option>
              <el-option
                :key="2"
                label="招商"
                :value="2"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="供应商:"
            prop="goodsRequest.merchantId"
            v-if="formData.goodsRequest.businessModel===2"
          >
            <el-select
              v-model="formData.goodsRequest.merchantId"
              placeholder="请选择"
              filterable
            >
              <el-option
                v-for="item in merchants"
                :key="item.supplyCode"
                :label="item.supplyName"
                :value="item.supplyCode"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="仓库:"
            prop="goodsRequest.cangku"
            :rules="formData.goodsRequest.businessModel===1?commonRules.notNullRule:[]"
          >
            <el-select
              v-model="formData.goodsRequest.cangku"
              placeholder="请选择"
              filterable
              clearable
            >
              <el-option
                v-for="item in warehouses"
                :key="item.ckdm"
                :label="item.merchantName"
                :value="item.ckdm+''"
                v-show="!item.ty"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="运费模板:"
            prop="goodsRequest.freightTemplateId"
          >
            <el-select
              v-model="formData.goodsRequest.freightTemplateId"
              placeholder="请选择"
              filterable
              clearable
            >
              <el-option
                :key="item.id"
                :label="item.name"
                :value="item.id"
                v-for="item in freightList"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="销售数量:"
            prop="goodsRequest.salesVolume"
          >
            <el-input
              type="number"
              v-model="formData.goodsRequest.salesVolume"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="标签:"
            prop="tempTagCheck"
          >
            <input
              type="checkbox"
              id="tag-more"
              class="tag-checkbox-group-switch"
              v-model="tagMore"
            />
            <el-checkbox-group
              v-model="tempTagCheck"
              class="tag-checkbox-group-more"
            >
              <el-checkbox
                v-for="(item, id) in tags"
                :key="id"
                :label="id"
              >{{item.name}}</el-checkbox>
              <label
                for="tag-more"
                class="tag-checkbox-group-more-btn"
                v-text="tagMore ? '收起' : '更多'"
              ></label>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
        <el-form
          :disabled="$route.query.pageType==='view'"
          :model="formData"
          :rules="rulesBase"
          ref="formBase2"
          size="medium"
          label-width="150px"
        >
          <el-form-item
            label="是否上架:"
            prop="goodsRequest.upshelf"
          >
            <el-switch
              v-model="formData.goodsRequest.upshelf"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-text="是"
              inactive-text="否"
              :active-value="1"
              :inactive-value="0"
              :disabled="formData.organizationId!==1"
            >
            </el-switch>
          </el-form-item>
          <template>
            <!-- <el-form-item label="是否自动上下架:" prop="goodsRequest.autoUpShelfFlag">
              <el-switch
                v-model="formData.goodsRequest.autoUpShelfFlag"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-text="是"
                inactive-text="否"
                :active-value="1"
                :inactive-value="0"
                :disabled="formData.organizationId!==1"
                @change="changeIsSell">
              </el-switch>
            </el-form-item> -->
            <el-form-item label="上下架时间:" :rules="commonRules.notNullRule">
              <el-date-picker
                type="datetime"
                style="width: 250px"
                v-model="formData.goodsRequest.autoUpShelfTime"
                placeholder="上架时间"
                value-format="yyyy-MM-dd HH:mm:ss">
              </el-date-picker> ~
              <el-date-picker
                type="datetime"
                style="width: 250px"
                v-model="formData.goodsRequest.autoDownShelfTime"
                placeholder="下架时间"
                value-format="yyyy-MM-dd HH:mm:ss">
              </el-date-picker>
            </el-form-item>
          </template>
          <el-form-item
            label="是否售卖:"
            prop="goodsRequest.isSell"
          >
            <el-switch
              v-model="formData.goodsRequest.isSell"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-text="是"
              inactive-text="否"
              :active-value="1"
              :inactive-value="0"
              :disabled="formData.organizationId!==1"
            >
            </el-switch>
          </el-form-item>
          <el-form-item
            label="开售时间:"
            prop="goodsRequest.sellTime"
            v-if="formData.goodsRequest.isSell === 0"
            :rules="commonRules.notNullRule"
          >
            <el-date-picker
              v-model="formData.goodsRequest.sellTime"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetime"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item
            label="是否在商城展示:"
            prop="goodsRequest.showApp"
          >
            <el-switch
              v-model="formData.goodsRequest.showApp"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-text="是"
              inactive-text="否"
              :active-value="1"
              :inactive-value="0"
              :disabled="formData.organizationId!==1"
            >
              >
            </el-switch>
          </el-form-item>
          <el-form-item
            label="是否允许被搜索:"
            prop="goodsRequest.isSearched"
            v-if="!isRedGoods"
          >
            <el-switch
              v-model="formData.goodsRequest.isSearched"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-text="是"
              inactive-text="否"
              :active-value="1"
              :inactive-value="0"
              :disabled="formData.organizationId!==1"
            >
            </el-switch>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane
        label="其他信息"
        name="other"
      >
        <el-form
          :model="formData"
          :rules="rulesOther"
          size="medium"
          ref="formOther"
          label-width="100px"
          :disabled="$route.query.pageType==='view'"
        >
          <el-form-item
            label="商品故事:"
            prop="goodsRequest.story"
          >
            <el-input
              type="textarea"
              v-model="formData.goodsRequest.story"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="商品详情:"
            prop="goodsRequest.comment"
          >
            <tinymce
              :height="960"
              v-model="formData.goodsRequest.comment"
            ></tinymce>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane
        label="商品属性"
        name="attr"
      >
        <el-form
          :model="formData"
          :rules="rulesAttr"
          size="medium"
          ref="formAttr"
          label-width="100px"
          :disabled="$route.query.pageType==='view'"
        >
          <!--<el-form-item label="商品类型:" prop="goodsTypeId">
                        <el-select v-model="formData.goodsTypeId" placeholder="请选择" @change="getAttrListByTypeId" clearable :disabled="!!isEdit">
                            <el-option v-for="item of goodsTypes" v-if="item.goodsTypeStatus" :key="item.id" :label="item.name" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="商品规格:">
                        <template v-if="goodsAttrList.length">
                            <div class="goods-attr-item" v-for="(item, index) in goodsAttrList">
                                <span>{{item.attrName}}：</span>
                                <el-select placeholder="请选择" v-model="tempGoodsAttr[`attrValue${index+1}`]" filterable clearable>
                                    <el-option v-for="subItem of item.attrValues.split('\n').filter(i=> i!=='')" :key="subItem" :label="subItem" :value="subItem"></el-option>
                                </el-select>
                            </div>
                            <el-button type="primary" size="small" plain @click="addGoodsAttr">添加规格</el-button>
                        </template>
                    </el-form-item>-->
          <el-form-item
            label="规格明细:"
            v-if="formData.attrList.length"
          >
            <div class="tool-bar">
              <template v-if="!setPropsTxt.length">
                批量设置：
                <el-button
                  type="text"
                  :disabled="!formData.goodsRequest.upshelf"
                  @click="setProps(['financePrice', '财务价'])"
                >财务价</el-button>
                <el-button
                  type="text"
                  :disabled="!formData.goodsRequest.upshelf"
                  @click="setProps(['costPrice', '成本价'])"
                >成本价</el-button>
                <el-button
                  type="text"
                  :disabled="!formData.goodsRequest.upshelf"
                  @click="setProps(['marketValue', '市场价'])"
                >市场价</el-button>
                <el-button
                  type="text"
                  :disabled="!formData.goodsRequest.upshelf"
                  @click="setProps(['price', '兰蜜价'])"
                >兰蜜价</el-button>
                <!--
                                <el-button type="text" :disabled="!formData.goodsRequest.upshelf" @click="setProps(['regionPrice', '大区价'])">大区价</el-button>
                                <el-button type="text" :disabled="!formData.goodsRequest.upshelf" @click="setProps(['directorPrice', '董事价'])">董事价</el-button>
                                <el-button type="text" :disabled="!formData.goodsRequest.upshelf" @click="setProps(['commission', '佣金数值'])">佣金数值</el-button>
                                -->
                <el-button
                  type="text"
                  :disabled="!formData.goodsRequest.upshelf"
                  @click="setProps(['maximumCommission', '最高佣金'])"
                >最高佣金</el-button>
                <el-button
                  type="text"
                  @click="changeShelfStatus"
                >上架</el-button>
                <!--<el-button type="text" :disabled="!formData.goodsRequest.upshelf" @click="setProps(['skuNumber', '库存数'])">库存数</el-button>-->
              </template>
              <template v-else>
                批量设置【{{setPropsTxt[1]}}】：
                <el-input
                  type="number"
                  size="small"
                  v-model="setPropsValue"
                  style="width: 200px;"
                ></el-input>
                <el-button
                  class="filter-item"
                  type="primary"
                  plain
                  @click="savePropsValue"
                  size="mini"
                >确定</el-button>
                <el-button
                  class="filter-item"
                  plain
                  size="mini"
                  @click="setPropsTxt=[]"
                >取消</el-button>
              </template>
            </div>
            <el-table
              :data="formData.attrList"
              ref="tables"
              @select-all="changeCkeckStatus"
              @select="changeCkeckStatus"
              border
              highlight-current-row
            >
              <el-table-column
                align="center"
                type="selection"
                label="全选"
                prop="skuChecked"
              ></el-table-column>
              <el-table-column
                align="center"
                label="图库"
                width="100"
                fixed
              >
                <template slot-scope="scope">
                  <div class="avatar-uploader">
                    <label
                      class="el-upload el-upload-text"
                      style="width: 80px; height: 80px; line-height: 82px"
                    >
                      <img
                        v-if="scope.row.skuImage"
                        :src="scope.row.skuImage"
                        alt=""
                      >
                      <i
                        v-if="!scope.row.skuImage"
                        class="el-icon-plus avatar-uploader-icon"
                      ></i>
                      <input
                        type="file"
                        class="el-upload__input"
                        accept="image/*"
                        @change="uploadAttrImg(scope.row, $event)"
                      >
                    </label>
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                v-for="item in tempTableOpts"
                align="center"
                :key="item.columnLabel"
                :label="item.columnLabel"
                min-width="100px"
                :prop="item.prop"
              >
              </el-table-column>
              <!--<el-table-column label="财务价" min-width="100px">
                                <template slot-scope="scope">
                                    <el-form-item :prop="'attrList['+scope.$index+'].financePrice'" :rules="commonRules.priceRuleNull" style="margin: 30px 0">
                                        <el-input type="number" v-model="scope.row.financePrice" style="width: 100%"></el-input>
                                    </el-form-item>
                                </template>
                            </el-table-column>
                            <el-table-column label="成本价" min-width="100px">
                                <template slot-scope="scope">
                                    <el-form-item :prop="'attrList['+scope.$index+'].costPrice'" :rules="commonRules.priceRuleNull" style="margin: 30px 0">
                                        <el-input type="number" v-model="scope.row.costPrice" style="width: 100%"></el-input>
                                    </el-form-item>
                                </template>
                            </el-table-column>-->
              <el-table-column
                align="center"
                label="市场价"
                min-width="100px"
              >
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'attrList['+scope.$index+'].marketValue'"
                    :rules="commonRules.priceRule"
                    style="margin: 30px 0"
                  >
                    <el-input
                      type="number"
                      v-model="scope.row.marketValue"
                      style="width: 100%"
                    ></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="销售价"
                min-width="100px"
              >
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'attrList['+scope.$index+'].price'"
                    :rules="commonRules.priceRule"
                    style="margin: 30px 0"
                  >
                    <el-input
                      type="number"
                      v-model="scope.row.price"
                      style="width: 100%"
                      @input.native="scope.row.price=$event.target.value;calcOtherPrice(scope.$index, '0')"
                    ></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="VIP价"
                min-width="100px"
              >
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'attrList['+scope.$index+'].regionPrice'"
                    :rules="commonRules.priceRule"
                    style="margin: 30px 0"
                  >
                    <el-input
                      type="number"
                      placeholder="自动生成"
                      v-model="scope.row.maximumCommission == 0?scope.row.price:scope.row.regionPrice"
                      style="width: 100%"
                      disabled
                    ></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="钻石价"
                min-width="100px"
              >
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'attrList['+scope.$index+'].diamondPrice'"
                    :rules="commonRules.priceRule"
                    style="margin: 30px 0"
                  >
                    <el-input
                      type="number"
                      placeholder="自动生成"
                      v-model="scope.row.maximumCommission == 0?scope.row.price:scope.row.diamondPrice"
                      style="width: 100%"
                      disabled
                    ></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="董事价"
                min-width="100px"
              >
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'attrList['+scope.$index+'].directorPrice'"
                    :rules="commonRules.priceRule"
                    style="margin: 30px 0"
                  >
                    <el-input
                      type="number"
                      placeholder="自动生成"
                      v-model="scope.row.maximumCommission == 0?scope.row.price:scope.row.directorPrice"
                      style="width: 100%"
                      disabled
                    ></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <!--<el-table-column align="center" label="佣金类型" min-width="120px">
                                <template slot-scope="scope">
                                    <el-select v-model="scope.row.commissionType">
                                        <el-option :key="1" label="数值(元)" :value="1"></el-option>
                                        <el-option :key="2" label="比例(%)" :value="2"></el-option>
                                    </el-select>
                                </template>
                            </el-table-column>
                            <el-table-column align="center" label="佣金数值" min-width="100px">
                                <template slot-scope="scope">
                                    <el-form-item :prop="'attrList['+scope.$index+'].commission'" :rules="scope.row.commissionType===1?commonRules.priceRule : commonRules.percentRule" style="margin: 30px 0">
                                        <el-input type="number" v-model="scope.row.commission" style="width: 100%"></el-input>
                                    </el-form-item>
                                </template>
                            </el-table-column>-->
              <el-table-column
                align="center"
                label="最高佣金"
                min-width="100px"
              >
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'attrList['+scope.$index+'].maximumCommission'"
                    :rules="commonRules.priceRuleZero"
                    style="margin: 30px 0"
                  >
                    <el-input
                      type="number"
                      placeholder="小于兰蜜价"
                      v-model="scope.row.maximumCommission"
                      style="width: 100%"
                      @input.native="scope.row.maximumCommission=$event.target.value;calcOtherPrice(scope.$index, '1')"
                      :disabled="isRedGoods"
                    ></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="库存数"
                prop="totalSkuNumber"
                min-width="100px"
              >
                <template slot-scope="scope">
                  {{scope.row.totalSkuNumber}}
                  <div
                    v-if="!scope.row.totalSkuNumber"
                    style="color: red"
                  >库存不足</div>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="已售"
                prop="soldNumber"
                min-width="100px"
              ></el-table-column>
              <el-table-column
                align="center"
                label="是否上架"
                width="80"
              >
                <template slot-scope="scope">
                  <el-switch
                    v-model="scope.row.upshelf"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    :active-value="1"
                    :inactive-value="0"
                    @change="changeSingleSellStatus(scope.row)"
                  >
                  </el-switch>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="排序"
                width="100"
              >
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'attrList['+scope.$index+'].attrSort'"
                    :rules="commonRules.sortRule"
                    style="margin: 30px 0"
                  >
                    <el-input
                      type="number"
                      v-model="scope.row.attrSort"
                      style="width: 100%"
                    ></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="操作"
                width="60"
                fixed="right"
              >
                <template
                  slot-scope="scope"
                  v-if="scope.row.isNewAdd"
                >
                  <a
                    href="javascript: void(0);"
                    class="el-icon-remove"
                    @click="delAttrVal(scope.$index)"
                  ></a>
                </template>
              </el-table-column>
            </el-table>
            <div
              class="tool-bar"
              v-if="formData.attrList.length>=7"
            >
              <template v-if="!setPropsTxt.length">
                批量设置：
                <el-button
                  type="text"
                  :disabled="!formData.goodsRequest.upshelf"
                  @click="setProps(['financePrice', '财务价'])"
                >财务价</el-button>
                <el-button
                  type="text"
                  :disabled="!formData.goodsRequest.upshelf"
                  @click="setProps(['costPrice', '成本价'])"
                >成本价</el-button>
                <el-button
                  type="text"
                  :disabled="!formData.goodsRequest.upshelf"
                  @click="setProps(['marketValue', '市场价'])"
                >市场价</el-button>
                <el-button
                  type="text"
                  :disabled="!formData.goodsRequest.upshelf"
                  @click="setProps(['price', '兰蜜价'])"
                >兰蜜价</el-button>
                <!--
                                <el-button type="text" :disabled="!formData.goodsRequest.upshelf" @click="setProps(['regionPrice', '大区价'])">大区价</el-button>
                                <el-button type="text" :disabled="!formData.goodsRequest.upshelf" @click="setProps(['directorPrice', '董事价'])">董事价</el-button>
                                <el-button type="text" :disabled="!formData.goodsRequest.upshelf" @click="setProps(['commission', '佣金数值'])">佣金数值</el-button>
                                -->
                <el-button
                  type="text"
                  :disabled="!formData.goodsRequest.upshelf"
                  @click="setProps(['maximumCommission', '最高佣金'])"
                >最高佣金</el-button>
                <el-button
                  type="text"
                  @click="changeShelfStatus"
                >上架</el-button>
                <!--<el-button type="text" :disabled="!formData.goodsRequest.upshelf" @click="setProps(['skuNumber', '库存数'])">库存数</el-button>-->
              </template>
              <template v-else>
                批量设置【{{setPropsTxt[1]}}】：
                <el-input
                  type="number"
                  size="small"
                  v-model="setPropsValue"
                  style="width: 200px;"
                ></el-input>
                <el-button
                  class="filter-item"
                  type="primary"
                  plain
                  @click="savePropsValue"
                  size="mini"
                >确定</el-button>
                <el-button
                  class="filter-item"
                  plain
                  size="mini"
                  @click="setPropsTxt=[]"
                >取消</el-button>
              </template>
            </div>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane
        label="评论列表"
        name="common"
      >
        <CommontTable
          v-if="commontGoods.length > 0"
          :goodsType="1"
          :goods="commontGoods"
        />
      </el-tab-pane>
      <el-tab-pane
        label="商品上下架记录"
        name="log"
      >
        <el-table :data="goodsLogList" v-loading="listLoading" header-row-class-name="table-header" element-loading-text="给我一点时间" border highlight-current-row>
          <el-table-column align="center" label="姓名" prop="operatorName" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" label="手机号" prop="operatorMobile" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" label="动作" prop="actionName" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" label="操作时间" prop="updateTime" show-overflow-tooltip></el-table-column>
        </el-table>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="listQuery.pageIndex"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="listQuery.pageSize"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="listTotal">
        </el-pagination>
      </el-tab-pane>
    </el-tabs>
    <div
      class="main-title"
      style="margin: 20px 0 0"
    >
      <h4 v-text="isEdit ? pageTypes[$route.query.pageType] : '商品新建'"></h4>
      <div class="btn-box">
        <el-button
          v-if="$route.query.pageType!=='view'"
          class="filter-item"
          type="success"
          size="small"
          :loading="btnLoading"
          @click="save"
        >保存</el-button>
        <el-button
          v-if="rightsButtons['downShelf'] && $route.query.pageType==='view' && formData.goodsRequest.upshelf === 1"
          class="filter-item"
          type="danger"
          size="small"
          :loading="btnLoading"
          @click="updateStatus"
        >下架</el-button>
        <el-button
          class="filter-item"
          type="primary"
          size="small"
          plain
          @click="$router.push({name: ($store.getters.organizationId===1&&$route.query.goodsType==2)?'commodityPreManage':'commodityManage'})"
        >返回</el-button>
        <el-button
          class="filter-item"
          type="warning"
          size="small"
          v-if="!isEdit"
          @click="clearData(1)"
          plain
        >清空数据缓存</el-button>
      </div>
    </div>
  </div>
</template>
<script>
import draggable from 'vuedraggable'
// import { debounce } from '@/utils/index';
import Sortable from 'sortablejs'
import {
  getCategoryTree,
  getMerchantWarehouse,
  getGoodsTypeList,
  getAttrByTypeId,
  getTagList,
  upload
} from '../../../api/common'
import treeToArray from '@/components/TreeTable/eval'
import Tinymce from '@/components/Tinymce'
import { regexp } from '../../../utils/tools'
import { getAllList } from '@/api/freight'
import CommontTable from '@/components/CommontTable'
const debounce = (fn, interval, immediately) => {
  let timeout
  return function () {
    const $this = this
    const $arguments = arguments
    if (!timeout) {
      if (immediately) {
        fn.apply($this, $arguments)
      }
    } else {
      clearTimeout(timeout)
      timeout = null
    }

    if (!timeout) {
      timeout = setTimeout(function () {
        clearTimeout(timeout)
        timeout = null
        fn.apply($this, $arguments)
      }, interval)
    }
  }
}
export default {
  name: 'commodityManageEdit',
  props: {
    id: { default: '' }
  },
  inject: ['reload'],
  components: {
    Tinymce,
    draggable,
    Sortable,
    CommontTable
  },
  data() {
    return {
      listLoading: false, // 商品上下架记录表格loading
      listTotal: 0, // 商品上下架记录 分页总数
      listQuery: { // 商品上下架记录 分页
        pageIndex: 1,
        pageSize: 10,
      },
      goodsLogList: [], // 商品上下架记录
      pageTypes: {
        view: '商品查看',
        edit: '商品编辑'
      },
      commontGoods: [], // 评论商品列表
      currentGoodsType: '',
      btnLoading: false,
      tab: 'base',
      isCorrectGoods:
        this.$store.getters.organizationId === 1 &&
        this.$route.query.goodsType == 1,
      categoryTree: [],
      merchants: [],
      warehouses: [],
      tags: [],
      goodsTypes: [],
      goodsAttrList: [],
      tagMore: false,
      tempTagCheck: [],
      tempTableOpts: [],
      tempGoodsAttr: {
        attrId1: '',
        attrValue1: '',
        attrId2: '',
        attrValue2: ''
      },
      setPropsTxt: '',
      setPropsValue: '',
      pageLoading: true,
      goods:{}, //商品数据
      formData: {
        userId: this.$store.getters.userId,
        organizationId: this.$store.getters.organizationId,
        goodsType: this.$route.query.goodsType,

        goodsRequest: {
          autoUpShelfTime: '',
          autoDownShelfTime: '',
          name: '',
          subName: '',
          serialNo: '',
          category: '',
          image: '',
          listCover: '',
          crushImage: '',
          goodsGalleryList: [],
          marketValue: '',
          price: '',
          regionPrice: '',
          directorPrice: '',
          maximumCommission: 0,
          salesVolume: 0,
          userQuantity: 0,
          upshelf: 0,
          autoUpShelfFlag: 0,
          timeRange: [],
          isSell: 0,
          intro: '',
          businessModel: this.$store.getters.organizationId !== 1 ? 2 : 1,
          showApp: 0,
          isSearched: 0,
          freightTemplateId: '', // 模板id
          taxName: '',
          taxCode: '',
          taxRate: '',
          firstUpSelfTime: ''
        },
        goodsAutoManage: {},
        attrList: [],
        goodsTypeId: ''
      },
      attrListBack: [],
      rulesBase: {
        'goodsRequest.name': [
          { required: true, message: '不能为空', trigger: 'change' },
          { max: 100, message: '不能超过100字符', trigger: 'change' }
        ],
        'goodsRequest.subName': [
          { required: true, message: '不能为空', trigger: 'change' },
          { max: 100, message: '不能超过100字符', trigger: 'change' }
        ],
        'goodsRequest.serialNo': [
          { required: true, message: '不能为空', trigger: 'change' },
          { max: 100, message: '不能超过100字符', trigger: 'change' }
        ],
        'goodsRequest.category': [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        'goodsRequest.firstUpSelfTime': [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        'goodsRequest.image': [
          { required: true, message: '请上传', trigger: 'change' }
        ],
        'goodsRequest.listCover': [
          { required: true, message: '请上传', trigger: 'change' }
        ],
        'goodsRequest.goodsGalleryList': [
          { required: true, message: '请上传', trigger: 'change' }
        ],
        'goodsRequest.marketValue': [
          { required: true, message: '不能为空', trigger: 'change' },
          {
            pattern: regexp.money,
            message: '价格必须大于0且最多两位小数',
            trigger: 'change'
          }
        ],
        'goodsRequest.price': [
          { required: true, message: '不能为空', trigger: 'change' },
          {
            pattern: regexp.money,
            message: '价格必须大于0且最多两位小数',
            trigger: 'change'
          }
        ],
        'goodsRequest.regionPrice': [
          { required: true, message: '不能为空', trigger: 'change' },
          {
            pattern: regexp.money,
            message: '价格必须大于0且最多两位小数',
            trigger: 'change'
          }
        ],
        'goodsRequest.directorPrice': [
          { required: true, message: '不能为空', trigger: 'change' },
          {
            pattern: regexp.money,
            message: '价格必须大于0且最多两位小数',
            trigger: 'change'
          }
        ],
        'goodsRequest.maximumCommission': [
          { required: true, message: '不能为空', trigger: 'change' },
          {
            pattern: regexp.zMoney,
            message: '佣金必须大于等于0且最多两位小数',
            trigger: 'change'
          }
        ],
        'goodsRequest.userQuantity': [
          { required: true, message: '不能为空', trigger: 'change' },
          {
            pattern: regexp.nNegativeInt,
            message: '必须为非负整数',
            trigger: 'change'
          }
        ],
        'goodsRequest.businessModel': [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        'goodsRequest.merchantId': [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        'goodsRequest.timeRange': [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        // 模板运费验证
        'goodsRequest.freightTemplateId': [
          { required: true, message: '请选择' }
        ],
         // 发票
        'goodsRequest.taxCode': [
          { required: true, message: '请选择' }
        ]
      },
      rulesOther: {
        'goodsRequest.story': [
          { required: true, message: '不能为空', trigger: 'change' }
        ],
        'goodsRequest.comment': [
          { required: true, message: '不能为空', trigger: 'change' }
        ]
      },
      rulesAttr: {
        goodsTypeId: [{ required: true, message: '请选择', trigger: 'change' }]
      },
      freightList: [], // 运费模板列表
      taxListOptions: [],
      tax: []
    }
  },
  computed: {
    isEdit() {
      return this.id
    },
    // taxTxt() {
    //   if (!this.formData.goodsRequest.taxCode) return ''
    //   // return (this.formData.goodsRequest.taxCode||'')
      // return (this.formData.goodsRequest.taxName || '') + '/' + (this.formData.goodsRequest.taxCode||'')
    // },
    taxTxt: {
      get: function () {
        return (this.formData.goodsRequest.taxName||'')
      },
      set: function (newValue) {
        this.formData.goodsRequest.taxName = newValue
      }
    },
    //是否是红药房的商品
    isRedGoods(){
      let redArr=[166, 167, 168, 169, 170, 171, 172];//红药房的分类id
      let id=this.formData.goodsRequest.category.split('_')[0];
      let isRed=redArr.includes(Number(id));
      return isRed;
    }
  },
  created() {
    if (this.isEdit) {
      this.getInfo()
    } else {
      let tempGoodsData = localStorage.getItem('tempGoodsData')
      let tempTagCheck = localStorage.getItem('tempTagCheck')
      let tempTableOpts = localStorage.getItem('tempTableOpts')
      let tempGoodsAttr = localStorage.getItem('tempGoodsAttr')
      let goodsAttrList = localStorage.getItem('goodsAttrList')

      if (tempGoodsData) {
        this.formData = JSON.parse(tempGoodsData)
      }
      if (tempTagCheck) {
        this.tempTagCheck = JSON.parse(tempTagCheck)
      }
      if (tempTableOpts) {
        this.tempTableOpts = JSON.parse(tempTableOpts)
      }
      if (tempGoodsAttr) {
        this.tempGoodsAttr = JSON.parse(tempGoodsAttr)
      }
      if (goodsAttrList) {
        this.goodsAttrList = JSON.parse(goodsAttrList)
      }
    }
    this.getCategoryTree()
    this.getMerchantWarehouseList()
    this.getTagList()
    this.getGoodsTypes()
    this.getAllTpl()
    this.getTaxList()
  },
  updated() {
    if (!this.isEdit) {
      // localStorage
      localStorage.setItem('tempGoodsData', JSON.stringify(this.formData))
      localStorage.setItem('tempTagCheck', JSON.stringify(this.tempTagCheck))
      localStorage.setItem('tempTableOpts', JSON.stringify(this.tempTableOpts))
      localStorage.setItem('tempGoodsAttr', JSON.stringify(this.tempGoodsAttr))
      localStorage.setItem('goodsAttrList', JSON.stringify(this.goodsAttrList))
    }
  },
  methods: {
    //分类修改
    categoryChange(e){
      if(this.isRedGoods){
        //佣金都置为0
        for (let s of this.formData.attrList) {
          s.maximumCommission=0;
        }
        this.formData.goodsRequest.isSearched=0;//是否允许被搜索设为否
      }
    },
    // 商品上下架记录列表
    getLogList () {
      this.request({
        url: '/bsnl-product/actionLog/page',
        method: 'post',
        data: { ...this.listQuery, typeCode: 'goods', foreignKey: this.$route.query.goodsId }
      }).then(({data2, totalCount}) => {
        this.goodsLogList = data2;
        this.listTotal = totalCount;
        this.listLoading = false;
      }).catch(err => {
        console.log(err);
        this.goodsLogList = [];
        this.listTotal = 0;
        this.listLoading = false;
      });
    },
    // 商品上下架记录 分页页数
    handleSizeChange (value) {
      this.listQuery.pageSize = value;
      this.getLogList()
    },
    // 商品上下架记录 分页页码
    handleCurrentChange(val){
      this.listQuery.pageIndex = val;
      this.getLogList();
    },
    // 获取模板列表
    getAllTpl() {
      getAllList()
        .then(res => {
          if (res.code == 0) {
            this.freightList = res.data
          } else {
            this.$message({
              type: 'error',
              message: res.msg,
              duration: 2000
            })
          }
        })
        .catch(err => {
          this.$message({
            type: 'error',
            message: '未知错误',
            duration: 2000
          })
        })
    },
    getInfo() {
      this.request({
        url: '/bsnl-product/goods/details',
        method: 'get',
        params: {
          id: this.id,
          userId: this.$store.getters.userId
        }
      })
        .then(({ data }) => {
          data.goods.freightTemplateId = data.goods.freightTemplateId
            ? data.goods.freightTemplateId + ''
            : ''
          let {
            goods,
            goodsAutoManage,
            goodsAttr,
            goodsTag,
            goodsTypeId
          } = data
          this.goods=goods;
          this.formData.goodsRequest = {
            ...goods,
            businessModel: goods.businessModel || '',
            cangku: goods.cangku || '',
            category: `${goods.categoryId}_${goods.categoryName}`,
            timeRange: []
          }
          if (!this.formData.goodsRequest.isSearched) {
            this.formData.goodsRequest.isSearched = 0
          }
          if (goodsAutoManage) {
            this.formData.goodsRequest.timeRange = [
              goodsAutoManage.startTime,
              goodsAutoManage.endTime
            ]
          }
          this.formData.goodsAutoManage = goodsAutoManage ? goodsAutoManage : {}

          this.tempTagCheck = goodsTag.map(item => item.tagId + '')
          this.formData.goodsTypeId = goodsTypeId
          this.formData.attrList = goodsAttr
          /*this.formData.attrList.map(item => {
            item.distributedSkuNumber = item.skuNumber
          });*/

          this.commontGoods.push({
            value: goods.goodsId,
            label: goods.name
          })
          this.currentGoodsType = this.$route.query.goodsType
          console.log(this.currentGoodsId, this.currentGoodsType)
          this.getAttrListByTypeId(goodsTypeId)
          this.pageLoading = false
        })
        .catch(err => {
          this.formData = {
            userId: this.$store.getters.userId,
            organizationId: this.$store.getters.organizationId,
            goodsType: this.$route.query.goodsType,

            goodsRequest: {
              name: '',
              subName: '',
              serialNo: '',
              category: '',
              image: '',
              listCover: '',
              crushImage: '',
              goodsGalleryList: [],
              marketValue: '',
              price: '',
              regionPrice: '',
              directorPrice: '',
              maximumCommission: 0,
              userQuantity: 0,
              upshelf: 0,
              autoUpShelfFlag: 0,
              timeRange: [],
              isSell: 0,
              showApp: 0,
              isSearched: 0,
              intro: '',
              businessModel: this.$store.getters.organizationId !== 1 ? 2 : 1,
              freightTemplateId: '',
              taxName: '',
              taxCode: '',
              taxRate: '',
              firstUpSelfTime: ''
            },
            goodsAutoManage: {},
            attrList: [],
            goodsTypeId: ''
          }
          this.pageLoading = false
        })
    },
    // 获取分类树
    getCategoryTree() {
      getCategoryTree()
        .then(({ data }) => {
          let tmp = data ? data : []
          this.categoryTree = treeToArray(tmp, {
            type: Boolean,
            default: false
          })
        })
        .catch(err => {
          this.categoryTree = []
        })
    },
    // 获取供应商、仓库列表
    getMerchantWarehouseList() {
      getMerchantWarehouse().then(({ data }) => {
        this.merchants = data.viewList.filter(item => item.supplyCode !== null)
        this.warehouses = data.viewList.filter(item => item.ckdm !== null)
      })
    },
    // 获取标签列表
    getTagList() {
      getTagList().then(({ data }) => {
        let arr = data ? data : []
        this.tags = {}
        for (let item of arr) {
          this.tags[item.id] = item
        }
      })
    },
    // 获取商品类型
    getGoodsTypes() {
      getGoodsTypeList()
        .then(({ data }) => {
          this.goodsTypes = data
        })
        .catch(err => {
          this.goodsTypes = []
        })
    },
    // 获取最新可分配库存
    syncSkuNumber(e) {
      // 修改选中状态
      if (e.name === 'attr') {
        this.formData.attrList.map(item => {
          item.skuChecked = false
          if (item.upshelf === 1) {
            item.skuChecked = true
            this.$refs.tables.toggleRowSelection(item, true)
          }
        })
      } else if (e.name === 'log') {
        this.getLogList()
      }
      /*if(e.name !== 'attr')
          return;
        let kucunList = this.formData.attrList.map(item => {
          return {
            sku: item.skuCode,
            sddm: 'bsnlApp'
          }
        });

        this.request({
          //url: `/bsnl-erp-product/goodsSku/syncSingeGoodsSkuToApp/${skuCode}`,
          url: `/bsnl-product/erp/bsnl/updateGetKucun`,
          method: 'post',
          data: {
            kucunList
          }
        }).then(({data2}) => {
          console.log(data2);
          this.formData.attrList.map(aItem => {
            let attr = data2.filter(item => item.skuCode === aItem.skuCode);
            if(attr && attr.length){
              aItem.totalSkuNumber = attr[0].distributableSkuNumber;
            }
          })

        }).catch(err => {
          console.log(err);
        });*/
    },

    updateStatus() {
      this.$confirm(`确定下架该商品`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.request({
            url: '/bsnl-product/goods/status',
            method: 'post',
            data: {
              id: this.id,
              upshelf: 0,
              isSell: 0,
              showApp: 0,
              isSearched: 0
            },
            headers: {
              authorKey: `${this.$route.name}DownShelf`
            }
          })
            .then(() => {
              this.$message.success('下架成功')
              history.pushState(
                {},
                '',
                this.$route.fullPath.replace('view', 'edit')
              )
              this.$route.query.pageType = 'edit'
              this.reload()
            })
            .catch(err => {
              this.$message.error(err)
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          })
        })
    },
    // 清空数据缓存
    clearData(reloadFlag) {
      localStorage.removeItem('tempGoodsData')
      localStorage.removeItem('tempTagCheck')
      localStorage.removeItem('tempTableOpts')
      localStorage.removeItem('goodsAttrList')
      if (reloadFlag) {
        this.reload()
      }
    },
    uploadSuccess(res) {
      this.formData.goodsRequest.image = this.replaceImgUrl(res.filePath)
    },
    uploadListCoverSuccess(res) {
      this.formData.goodsRequest.listCover = this.replaceImgUrl(res.filePath)
    },
    uploadCrushImageSuccess(res) {
      this.formData.goodsRequest.crushImage = this.replaceImgUrl(res.filePath)
    },
    uploadImg(event) {
      const file = event.target.files[0]
      this.picFileUpload(file, (res, file, type) => {
        this.formData.goodsRequest.goodsGalleryList.push({
          url: this.replaceImgUrl(res.filePath),
          goodsId:
            this.isEdit && this.formData.goodsRequest
              ? this.formData.goodsRequest.goodsId
              : undefined,
          type: type
        })
      })
    },
    delImg(index) {
      this.formData.goodsRequest.goodsGalleryList.splice(index, 1)
    },
    uploadAttrImg(item, event) {
      const file = event.target.files[0]
      this.picFileUpload(file, res => {
        this.$set(item, 'skuImage', this.replaceImgUrl(res.filePath))
      })
    },
    // 根据兰蜜价和最高佣金计算大区价和董事价
    calcPrice() {
      let query = {
        lmPrice: this.formData.goodsRequest.price,
        highestCommission: this.formData.goodsRequest.maximumCommission
      }
      this.calcRDPrice(query, data => {
        this.formData.goodsRequest.regionPrice = data.regionPrice
        this.formData.goodsRequest.directorPrice = data.directorPrice
      })
    },
    // 根据兰蜜价和最高佣金计算大区价和董事价
    calcOtherPrice: debounce(function (index, flag) {
      if (flag === '1') {
        this.request({
          url: '/bsnl-product/goods/isNotParticipateActivity',
          method: 'get',
          params: {
            goodsId: this.$route.query.goodsId
          }
        }).catch(err => {
          console.error(err)
        })
      }
      let query = {
        lmPrice: this.formData.attrList[index].price,
        highestCommission: this.formData.attrList[index].maximumCommission
      }
      this.calcRDPrice(query, data => {
        this.$set(this.formData.attrList[index], 'regionPrice', data.regionPrice)
        this.$set(this.formData.attrList[index], 'directorPrice', data.directorPrice)
        this.$set(this.formData.attrList[index], 'diamondPrice', data.diamondPrice)
      })
    }, 500, false),
    changeCkeckStatus(selection) {
      this.attrListBack = selection
    },

    //改变勾选中的sku的上架状态
    changeShelfStatus() {
      this.$confirm('是否更改选中规格的状态为 上架?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          let status
          this.formData.attrList.map(item => {
            status = false
            this.attrListBack.map(thing => {
              // false为没有相同
              if (item.id === thing.id && status === false) {
                item.skuChecked = true
                item.upshelf = 1
                status = true
              } else if (status === false) {
                item.skuChecked = false
                item.upshelf = 0
              }
            })
          })
          this.$message({
            type: 'success',
            message: '已批量更改上架状态，请点击保存完成操作!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消更改'
          })
        })
    },

    // 改变sku勾选状态
    changeSingleSellStatus(item) {
      item.skuNumber = 0
      console.log(item.upshelf)
      if (item.upshelf === 0) {
        item.skuChecked = false
        this.$refs.tables.toggleRowSelection(item, false)
      } else if (item.upshelf === 1) {
        item.skuChecked = true
        this.$refs.tables.toggleRowSelection(item, true)
      }
    },
    // changeIsSell() {
      // if (
      //   !(
      //     this.formData.goodsRequest.upshelf ||
      //     this.formData.goodsRequest.autoUpShelfFlag
      //   )
      // ) {
      //   this.formData.goodsRequest.isSell = 0
      //   this.formData.goodsRequest.showApp = 0
      //   this.formData.goodsRequest.isSearched = 0
      // } else if (this.formData.goodsRequest.upshelf == 1) {
      //   this.formData.goodsRequest.showApp = 1
      // }

      /*if(this.formData.goodsRequest.upshelf){
          this.formData.attrList.map(item => {
            item.skuNumber = item.totalSkuNumber
          })
        } else {
          this.formData.attrList.map(item => {
            item.skuNumber = 0
          })
        }*/
    // },
    // 根据商品类型获取商品规格
    getAttrListByTypeId(id) {
      if (!id) {
        this.goodsAttrList = []
        return
      }
      getAttrByTypeId({ goodsTypeId: id })
        .then(({ data }) => {
          // console.log(data, 'AttrList');
          this.goodsAttrList = data || []
          this.tempTableOpts = []
          data.map((item, index) => {
            this.tempGoodsAttr[`attrId${index + 1}`] = item.id
            this.tempTableOpts.push({
              columnId: item.id,
              columnLabel: item.attrName,
              prop: `attrValue${index + 1}`
            })
          })
        })
        .catch(err => {
          this.goodsAttrList = []
        })
    },
    // 添加规格
    addGoodsAttr() {
      console.log(this.tempGoodsAttr)
      let isExist = this.formData.attrList.some(
        item =>
          item.attrValue1 === this.tempGoodsAttr.attrValue1 &&
          item.attrValue2 === this.tempGoodsAttr.attrValue2
      )
      if (isExist) {
        this.$message.warning('已存在该规格')
      } else if (
        this.tempGoodsAttr.attrValue1 &&
        this.tempGoodsAttr.attrValue2
      ) {
        if (this.isEmpty(this.formData.goodsRequest.serialNo)) {
          this.$message.info('请在基础信息里先填写商品款号')
          // this.tab = 'base';
          return false
        }
        let data = {
          attrId: this.tempGoodsAttr.attrId1,
          attrValue: this.tempGoodsAttr.attrValue1,
          attrId2: this.tempGoodsAttr.attrId2,
          attrValue2: this.tempGoodsAttr.attrValue2,
          serialNo: this.formData.goodsRequest.serialNo,
          organizationId: this.formData.organizationId,
          goodsType: this.$route.query.goodsType,
          pageIndex: 1,
          pageSize: 15
        }
        let attrItem = {
          skuImage: '',
          ...this.tempGoodsAttr,
          financePrice: this.$store.getters.organizationId === 1 ? '' : 1,
          costPrice: this.$store.getters.organizationId === 1 ? '' : 1,
          price: this.$store.getters.organizationId === 1 ? '' : 1,
          marketValue: this.$store.getters.organizationId === 1 ? '' : 1,
          regionPrice: this.$store.getters.organizationId === 1 ? '' : 1,
          directorPrice: this.$store.getters.organizationId === 1 ? '' : 1,
          commissionType: 1,
          commission: this.$store.getters.organizationId === 1 ? '' : 1,
          maximumCommission: this.$store.getters.organizationId === 1 ? 0 : 1,
          isNew:
            this.$store.getters.organizationId === 1 &&
            this.$route.query.goodsType == 1
              ? 0
              : 1,
          isNewAdd: 1,
          skuNumber: 0,
          totalSkuNumber: 0,
          distributedSkuNumber: 0,
          upshelf: 1,
          attrSort: ''
        }
        this.request({
          url: '/bsnl-product/goodssku/query',
          method: 'post',
          data
        })
          .then(({ data, totalCount }) => {
            if (totalCount) {
              attrItem.isNew = 0
              attrItem.totalSkuNumber = data[0].distributableSkuNumber
              this.formData.attrList.push(attrItem)
              this.tempGoodsAttr.attrValue1 = ''
              this.tempGoodsAttr.attrValue2 = ''
            } else if (
              this.$store.getters.organizationId === 1 &&
              this.$route.query.goodsType == 2
            ) {
              attrItem.totalSkuNumber = 0
              this.formData.attrList.push(attrItem)
              this.tempGoodsAttr.attrValue1 = ''
              this.tempGoodsAttr.attrValue2 = ''
            } else {
              this.$message.warning('该商品规格不存在')
            }
          })
          .catch(err => {
            this.$message.error('服务器异常')
            attrItem.totalSkuNumber = 0
          })
      } else {
        if (this.tempGoodsAttr.attrValue1 === '') {
          this.$message.warning(`请选择${this.tempTableOpts[0].columnLabel}`)
        } else {
          this.$message.warning(`请选择${this.tempTableOpts[1].columnLabel}`)
        }
      }
    },
    // 删除属性
    delAttrVal(index) {
      this.$confirm(`确定要删除吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.formData.attrList.splice(index, 1)
          this.$message.success('删除成功')
        })
        .catch(err => {
          console.log(err)
        })
    },
    // 批量设置
    setProps(prop) {
      this.setPropsTxt = prop
      this.setPropsValue = ''
    },
    savePropsValue() {
      let msg =
        this.setPropsTxt[0] === 'skuNumber'
          ? '库存数必须为正整数'
          : '请输入合法的数值(最多保留两位小数)'
      let reg =
        this.setPropsTxt[0] === 'skuNumber'
          ? regexp.positiveInt
          : this.setPropsTxt[0] === 'maximumCommission'
          ? regexp.zMoney
          : regexp.money
      if (this.setPropsValue && this.setPropsValue.match(reg)) {
        this.formData.attrList.map(item => {
          if (this.setPropsTxt[0] === 'skuNumber' && !item.upshelf) {
            item.skuNumber = 0
          } else {
            item[this.setPropsTxt[0]] = this.setPropsValue
          }
        })
        this.setPropsTxt = []
        this.formData.attrList.map(item => {
          let query = {
            lmPrice: item.price,
            highestCommission: item.maximumCommission
          }
          this.calcRDPrice(query, data => {
            item.regionPrice = data.regionPrice
            item.directorPrice = data.directorPrice
          })
        })
      } else {
        this.$message.warning(
          this.setPropsValue ? msg : '请输入' + this.setPropsTxt[1]
        )
      }
    },
    save() {
       console.log(this.formData)
      this.$refs.formBase.validate(validBase => {
        if (!validBase) {
          this.tab = 'base'
          return false
        }
        this.$refs.formBase2.validate(validBase2 => {
          if (!validBase2) {
            this.tab = 'base'
            return false
          }

          this.$refs.formOther.validate(validOther => {
            if (!validOther) {
              this.tab = 'other'
              return false
            }
            this.$refs.formAttr.validate(validAttr => {
              if (!validAttr) {
                this.tab = 'attr'
                return false
              }

              if (!this.formData.attrList.length) {
                this.$message.warning('商品属性不能为空')
                return false
              }
              if ((!this.formData.goodsRequest.autoUpShelfTime&&this.formData.goodsRequest.upshelf===0)||(!this.formData.goodsRequest.autoDownShelfTime&&this.formData.goodsRequest.upshelf===0)) {
                this.$message.warning('上下架时间不能为空')
                return false
              }
              if (new Date(this.formData.goodsRequest.autoUpShelfTime) > new Date(this.formData.goodsRequest.autoDownShelfTime)) {
                this.$message.warning('下架时间必须大于上架时间')
                return false
              }
              this.btnLoading = true
              this.formData.tagList = this.tempTagCheck.map(item => ({
                tagId: item
              }))
              let categoryArr = this.formData.goodsRequest.category.split('_')
              this.formData.goodsRequest.categoryId = categoryArr[0]
              this.formData.goodsRequest.categoryName = categoryArr[1]
              let timeRange = this.formData.goodsRequest.timeRange
              if (timeRange && timeRange.length > 0) {
                this.formData.goodsAutoManage.startTime = timeRange[0]
                this.formData.goodsAutoManage.endTime = timeRange[1]
              }
              this.formData.goodsRequest.freightTemplateId = Number(
                this.formData.goodsRequest.freightTemplateId
              )
              if (this.formData.goodsRequest.upshelf === 1) {
                this.formData.goodsRequest.autoUpShelfTime = ''
                this.formData.goodsRequest.autoDownShelfTime = ''
              }
              this.formData.attrList.forEach((item, index) =>{
                if (item.maximumCommission == 0) {
                  item.regionPrice = item.price
                  item.diamondPrice = item.price
                  item.directorPrice = item.price
                }
              })
              console.log(this.formData)
              this.request({
                url: this.isEdit
                  ? '/bsnl-product/goods/update'
                  : '/bsnl-product/goods/create',
                method: 'post',
                data: this.formData
              })
                .then((res) => {
                  if (res.status === 200) {
                    this.$message.success(
                      this.isEdit ? '编辑商品成功' : '新建商品成功'
                    )
                    if (!this.isEdit) {
                      //清空缓存
                      this.clearData()
                    }
                    this.$router.push({
                      name:
                        this.formData.organizationId === 1 &&
                        this.formData.goodsType == 2
                          ? 'commodityPreManage'
                          : 'commodityManage'
                    })
                  }
                  this.btnLoading = false
                })
                .catch(err => {
                  console.error(err)
                  this.btnLoading = false
                })
            })
          })
        })
      })
    },
    // 获取税收分类
    getTaxList(){
      this.request({
          url: '/invoice-web-manage/invoice/tax-item/all',
          method: 'get',
      }).then((res) => {
        this.taxListOptions = res.data
      }).catch(err => {
        console.log(err)
        this.taxListOptions = []
      })
    },
    getVal(val){
      let temVal = this.taxListOptions.find(i => i.taxName === val[0])
      let firstObj = []
      if (temVal && temVal.children){
        firstObj = temVal.children
      }
      for(let i = 1; i < val.length; i++){
        temVal = firstObj.find(item => item.taxName === val[i])
        if (temVal && temVal.children){
          firstObj = temVal.children
        }
      }
      this.formData.goodsRequest.taxName = temVal.taxName
      this.formData.goodsRequest.taxCode = temVal.taxCode
      this.formData.goodsRequest.taxRate = temVal.taxRate
    }
  }
}
</script>
<style lang="scss">
.commodity-manage-edit {
  .hide-close {
    .el-icon-circle-close {
      display: none;
    }
  }
  .avatar-uploader .el-upload,
  .upload-img-list li,
  .upload-img-list .upload-btn {
    width: 120px;
    height: 120px;
    line-height: 118px;
  }
  .upload-img-list .img-preview .img-preview-mask .mask-btn {
    margin-top: 47px;
    line-height: 36px;
    text-align: center;
  }
  .goods-attr-item {
    display: inline-block;
    margin-right: 15px;
    .el-select,
    .el-input {
      max-width: 196px;
    }
  }
  .el-table__row {
    .el-input {
      width: 100%;
    }
  }
  .tool-bar {
    border: 1px solid #efefef;
    padding: 10px;
    .batchSet {
      color: #409eff;
      padding: 5px;
      cursor: pointer;
    }
  }
  .cascader-m {
    // .el-cascader {
    //   // position: absolute;
    //   // top: 0;
    //   // left: 0;
    //   // opacity: 0;
    // }
    .code {
      margin-left: 10px;
    }
  }
}
</style>
